package com.qf.security1.filters;

import com.alibaba.fastjson.JSON;
import com.qf.security1.pojo.R;
import com.qf.security1.utils.JwtUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    public LoginFilter(AuthenticationManager authenticationManager) {
        setAuthenticationManager(authenticationManager);
    }

    /**
     * 登录成功后的回调
     * @param request
     * @param response
     * @param chain
     * @param authResult
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        //签发token - jwt串
        User user = (User) authResult.getPrincipal();
        String username = user.getUsername();
        Collection<GrantedAuthority> authorities = user.getAuthorities();

        //当前用户自定义的载荷信息
        Map map = new HashMap();
        if (authorities != null){
            List<String> roles = authorities.stream()
                    //将GrantedAuthority类型的流转换成String类型的流对象
                    .map(authority -> authority.getAuthority())
                    //将Stream流对象转换成集合对象
                    .collect(Collectors.toList());
            //当前用户的角色
            map.put("roles",roles);
        }
        //当前用户用户名
        map.put("username",username);

        String jwt = JwtUtils.createToken(map, username);

        R r = R.success(jwt);
        response.getWriter().write(JSON.toJSONString(r));
    }

    /**
     * 登录失败后的回调
     * @param request
     * @param response
     * @param failed
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        R r = R.fail("用户名或密码错误");

        response.getWriter().write(JSON.toJSONString(r));
    }
}
